<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">交易管理</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div style="margin-top: 20px;">
    <!-- 搜索栏 -->
    <el-row :gutter="20" class="search-bar">
      <el-col :span="8">
        <el-input
          v-model="searchQuery"
          placeholder="按名称搜索产品"
          clearable
        />
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-search" @click="searchProducts">
          搜索
        </el-button>
      </el-col>
    </el-row>

    <!-- 布局: 左边是添加/编辑表单，右边是商品列表 -->
    <el-row :gutter="20" class="main-content">
      <!-- 添加/编辑表单 -->
      <el-col :span="8">
        <el-card>
          <h2>{{ isEditMode ? '编辑产品' : '添加产品' }}</h2>
          <el-form :model="product">
            <el-form-item label="名称">
              <el-input v-model="product.name" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="product.description" />
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number v-model="product.price" :min="0" />
            </el-form-item>
            <el-form-item label="库存数量">
              <el-input-number v-model="product.quantity" :min="0" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">
                {{ isEditMode ? '更新' : '添加' }}
              </el-button>
              <el-button @click="clearForm">清空</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 商品列表 -->
      <el-col :span="16">
        <el-card>
          <h2>产品列表</h2>
          <el-table :data="paginatedProducts" style="width: 100%">
            <el-table-column prop="id" label="ID" width="50"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column prop="quantity" label="库存数量"></el-table-column>
            <el-table-column label="操作" width="220">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="editProduct(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="deleteProduct(scope.row.id)"
                  >删除</el-button
                >
                <el-button
                  size="mini"
                  type="warning"
                  @click="decrementQuantity(scope.row.id)"
                  >减少库存</el-button
                >
                <el-button
                  size="mini"
                  type="success"
                  @click="incrementQuantity(scope.row.id, 1)"
                  >增加库存</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="products.length"
          >
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      products: [],
      product: this.getEmptyProduct(),
      searchQuery: "",
      currentPage: 1,
      pageSize: 5,
    };
  },
  computed: {
    isEditMode() {
      return !!this.product.id;
    },
    paginatedProducts() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.products.slice(start, end);
    },
  },
  methods: {
    getEmptyProduct() {
      return {
        id: null,
        name: "",
        description: "",
        price: 0,
        quantity: 0,
      };
    },
    fetchProducts() {
      axios.get("http://localhost:8080/api/products/all").then((response) => {
        this.products = response.data;
      });
    },
    submitForm() {
      if (this.isEditMode) {
        axios
          .put(
            `http://localhost:8080/api/products/update/${this.product.id}`,
            this.product
          )
          .then(() => {
            this.fetchProducts();
            this.clearForm();
          });
      } else {
        axios.post("http://localhost:8080/api/products/new", this.product).then(
          () => {
            this.fetchProducts();
            this.clearForm();
          }
        );
      }
    },
    clearForm() {
      this.product = this.getEmptyProduct();
    },
    editProduct(product) {
      this.product = { ...product };
    },
    deleteProduct(id) {
      axios.delete(`http://localhost:8080/api/products/delete/${id}`).then(() => {
        this.fetchProducts();
      });
    },
    decrementQuantity(id) {
      axios.put(`http://localhost:8080/api/products/decrement/${id}`).then(() => {
        this.fetchProducts();
      });
    },
    incrementQuantity(id, amount) {
      axios
        .put(`http://localhost:8080/api/products/increment/${id}`, null, {
          params: { amount },
        })
        .then(() => {
          this.fetchProducts();
        });
    },
    searchProducts() {
      axios
        .get("http://localhost:8080/api/products/search", {
          params: { name: this.searchQuery },
        })
        .then((response) => {
          this.products = response.data;
        });
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
  },
  created() {
    this.fetchProducts();
  },
};
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.main-content {
  margin-top: 20px;
}

.el-input,
.el-button {
  width: 100%;
}

.el-card {
  padding: 20px;
}
</style>
